package com.scpii.api.common.auth.token;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.scpii.api.common.auth.AuthorizationRequest;
import com.scpii.api.common.auth.ClientAuthentication;
import com.scpii.api.common.auth.DefaultAuthorizationRequest;
import com.scpii.api.common.auth.client.ClientDetailsService;

public abstract class AbstractTokenGranter implements TokenGranter {

	protected final Log logger = LogFactory.getLog(getClass());

	private final AuthorizationServerTokenServices tokenServices;

	private final ClientDetailsService clientDetailsService;

	private final String grantType;

	protected AbstractTokenGranter(
			AuthorizationServerTokenServices tokenServices,
			ClientDetailsService clientDetailsService, String grantType) {
		this.clientDetailsService = clientDetailsService;
		this.grantType = grantType;
		this.tokenServices = tokenServices;
	}

	public AuthAccessToken grant(String grantType,
			AuthorizationRequest authorizationRequest) {

		if (!this.grantType.equals(grantType)) {
			return null;
		}

		String appId = authorizationRequest.getAppId();
		logger.debug("Getting access token for: " + appId);
		return getAccessToken(authorizationRequest);

	}

	protected AuthAccessToken getAccessToken(
			AuthorizationRequest authorizationRequest) {
		DefaultAuthorizationRequest outgoingRequest = new DefaultAuthorizationRequest(
				authorizationRequest);
		outgoingRequest.setApproved(true);
		ClientAuthentication clientAuthentication = getClientAuthentication(outgoingRequest);
		clientDetailsService.storeDevice(outgoingRequest, clientAuthentication);
		clientDetailsService.checkServiceIsExpired(clientAuthentication);
		return tokenServices.createAccessToken(clientAuthentication);
	}

	protected ClientAuthentication getClientAuthentication(
			AuthorizationRequest authorizationRequest) {
		return new ClientAuthentication(authorizationRequest, null);
	}

	protected AuthorizationServerTokenServices getTokenServices() {
		return tokenServices;
	}

}
